package org.aplikator.server.descriptor;

import org.aplikator.client.shared.data.Record;
import org.aplikator.server.Context;
import org.aplikator.server.persistence.PersisterTriggers;

public class SubView extends View {
    private View masterView;
    private Property<String> discriminator;

    public SubView(View masterView, Property<String> discriminator, Enum<?> value) {
        super(masterView, value.name());
        this.masterView = masterView;
        this.discriminator = discriminator;
        this.setPersistersTriggers(new SubPersisterTriggers(discriminator, value));
        this.addQueryDescriptor(value.name(), value.name(), discriminator.EQUAL(value.name()));
    }

    public Property<String> getDiscriminator() {
        return discriminator;
    }


    protected class SubPersisterTriggers implements PersisterTriggers {
        private String value;
        Property<String> discriminator;

        protected SubPersisterTriggers(Property<String> discriminator, Enum<?> value) {
            this.value = value.name();
            this.discriminator = discriminator;
        }

        @Override
        public void onCreate(Record record, Context ctx) {
            discriminator.setValue(record, value);
            masterView.getPersisterTriggers().onCreate(record, ctx);
        }

        @Override
        public void onUpdate(Record record, Context ctx) {
            masterView.getPersisterTriggers().onUpdate(record, ctx);
        }

        @Override
        public void afterCommit(Record record, Context ctx) {
            masterView.getPersisterTriggers().afterCommit(record, ctx);
        }

        @Override
        public void onDelete(Record record, Context ctx) {
            masterView.getPersisterTriggers().onDelete(record, ctx);
        }

        @Override
        public void onLoad(Record record, Context ctx) {
            masterView.getPersisterTriggers().onLoad(record, ctx);
        }

        @Override
        public void onPrepare(Record record, boolean isCopy, Context ctx) {
            masterView.getPersisterTriggers().onPrepare(record, isCopy, ctx);
        }
    }
}
